import { TableColumn } from "@table/interface";
import { useData } from "@table/hooks/useData";
import { SORT_DESC, SORT_ASC } from "@table/constant";
// let preColumn: any = {};
export const useSort = () => {
  const { searchOptions, eventBus, tableColumns, setCurrentPagination } = useData();

  // 置空上一个选中排序
  const clearSortHandler = (newColumn: TableColumn) => {
    tableColumns.value.forEach(item => {
      if (item.key != newColumn.key) {
        item.sortType = "";
      }
    });
    // if (preColumn.key != newColumn.key) {
    //   preColumn.sortType = "";
    // }
  };

  const sortHandler = (column: TableColumn) => {
    clearSortHandler(column);
    // preColumn = column;
    searchOptions.value.sortTable = column.tableName as string;
    searchOptions.value.sortFiled = column.key as string;
    if (!column.sortType) {
      column.sortType = SORT_DESC;
      searchOptions.value.sortType = SORT_DESC;
    } else if (column.sortType === SORT_DESC) {
      column.sortType = SORT_ASC;
      searchOptions.value.sortType = SORT_ASC;
    } else if (column.sortType === SORT_ASC) {
      column.sortType = "";
      searchOptions.value.sortType = "";
      searchOptions.value.sortTable = "";
      searchOptions.value.sortFiled = "";
    }
    setCurrentPagination();
    eventBus.emit("refresh");
  };
  return {
    sortHandler
  };
};
